<?php
namespace App\Services\Core\Store\Duke;

use App\Helpers\RestResponseFactory;
use App\Helpers\RestUtils;
use App\Helpers\Utils;
use App\Models\Factory\ThirdapilogFactory;
use App\Models\Factory\UserLoanQuotaFactory;
use App\Models\Orm\Identity;


/**
 * 嘟克贷款对接
 * Class DukeService
 * @package App\Services\Core\Store\Duke
 */
class DukeService
{

    /**
     * 筛选用户
     * @param $data
     */
    public static function filterUser($userphone)
    {
        $user_identity = Identity::where('userphone',$userphone)->first();

        if(empty($user_identity))
        {
            return RestResponseFactory::ok(RestUtils::getStdObj(),1005,1005,RestUtils::getErrorMessage(1005));

        }

        // 添加可投放城市限制
        if (in_array($user_identity['city'], DukeConfig::$limitCity)) {
            self::Send($user_identity);
        }

    }



    /**
     * 向合作方发送数据
     * @return mixed
     */
    public static function Send($data)
    {
        // 获取用户贷款额度
        $loanMoney = self::getUserLoadMoney($data['userphone']);

        // 声明sign
        $sign = self::sign($data);

        // 声明用户信息
        switch ($data['has_house']) {
            case 1:
                $Houes = 3;
                break;
            case 2:
                $Houes = 1;
                break;
            default:
                $Houes = 2;
                break;
        }
        switch ($data['has_car']) {
            case 1:
                $Car = 3;
                break;
            case 2:
                $Car = 1;
                break;
            default:
                $Car = 2;
                break;
        }
        switch ($data['professional']) {
            case 3:
                $Hire = 6;
                break;
            case 4:
                $Hire = 3;
                break;
            case 5:
                $Hire = 4;
                break;
            default:
                $Hire = $data['professional'];
                break;
        }
        $sendParams = [
            'Name'       => $data['name'],
            'Birthday'   => $data['birthday'],
            'Sex'        => $data['sex'],
            'Phone'      => $data['userphone'],
            'IP'         => Utils::ipAddress(),
            'City'       => $data['city'].'市',
            'LoanAmount' => intval($loanMoney),
            'LoanTime'   => 3,
            'Houes'      => $Houes,
            'Car'        => $Car,
            'XyCard'     => ($data['is_credit'] == 1)? 2 : 1,
            'Payway'     => $data['wage'],
            'Hire'       => $Hire,
            'Wage'       => $data['month_money'],
            'MID'        => 0,
            'SheBaoTime' => ($data['social_security'] == 1)? 3 : 1,
            'EPFTime'    => $data['accumulation_fund'],
            'IDCard'     => $data['idcard'],
            'Shouxian'   => ($data['has_issurance'] == 1)? 2 : 1,
            'IsWeiLiDai' => 0
        ];

        // 声明请求链接和get参数
        $url = DukeConfig::$url_test."?c=".DukeConfig::$merchantId_test."&t=loan&v=$sign&b=";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $sendParams);

        $res = curl_exec($ch);
        if (curl_errno($ch)) {
            dd(curl_error($ch));
        }
        curl_close($ch);

        $response = json_decode($res,true);
        // 创建推送日志
        $createlogdata = array(
            'uid'          => $data['uid'],
            'userphone'    => $data['userphone'],
            'code'         => $response['errCode'],
            'message'      => $response['errMsg'],
            'status'       => ($response['errCode'] == '1') ? 1 : 2,
            'type'         => 11,
            'created_at'   => date('Y-m-d H:i:s')
        );
        ThirdapilogFactory::createlog($createlogdata);

    }


    /**
     * 嘟克签名生成
     * @param  $data 签名生成所需数据
     * @return Sign  签名
     */

    public static function sign($data)
    {
        // sign=MD5加密字符串（生日+手机+渠道ID+ key）
        return md5($data['birthday'].$data['userphone'].DukeConfig::$merchantId_test.DukeConfig::$key_md5);
    }


    /**
    * 查询用户申请贷款额度
    *
    */
    public static function getUserLoadMoney($userphone)
    {
        // 贷款额度（单位：万）
        $LoanAmount = UserLoanQuotaFactory::getUserLoanQuota($userphone);
        $Amount = $LoanAmount != false&&isset($LoanAmount['quota_money']) ? $LoanAmount['quota_money'] : 0;
        $LoanAmount = round($Amount/10000);
        return $LoanAmount ? : 1;
    }




}
